package wetalk.software.bupt.com.wetalk.BroadcastReceiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import wetalk.software.bupt.com.wetalk.DB.WeTalkDB;
import wetalk.software.bupt.com.wetalk.application.MyApplication;
import wetalk.software.bupt.com.wetalk.model.po.User;

public class PullFriReceiver extends BroadcastReceiver {
    private static final String TAG="PullFriReceiver";
    @Override
    public void onReceive(Context context, Intent intent) {
        String content=intent.getStringExtra("content");
        String type=intent.getStringExtra("type");

        SharedPreferences.Editor editor=MyApplication.getContext().getSharedPreferences("data",Context.MODE_PRIVATE).edit();
        WeTalkDB.create(MyApplication.getContext()).deleteAllFri();

        try {
            JSONArray jsonArray=new JSONArray(content);
            for (int i = 0; i <jsonArray.length() ; i++) {
                JSONObject obj=jsonArray.getJSONObject(i);
                User user=new User();
                user.setUserId(obj.getString("id"));
                user.setUserName(obj.getString("name"));
                user.setDepartment(obj.getString("department"));
                user.setPhone(obj.getString("phone"));
                user.setEmail(obj.getString("email"));
                if(type.equals("pullFri"))
                    WeTalkDB.create(MyApplication.getContext()).addFri(user);
                else
                    WeTalkDB.create(MyApplication.getContext()).addUserTable(user);
            }
            editor.putString("display","yes");
            editor.apply();

        } catch (JSONException e) {
            e.printStackTrace();
        }


    }
}
